home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2232 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  57 lines

  1. Path: news.itd.umich.edu!not-for-mail
  2. From: jlthomas@umd.umich.edu (Jeffrey L. Thomas)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can't figure this out
  5. Date: 19 Jan 1996 18:25:09 -0500
  6. Organization: Univerisity of Michigan - Dearborn
  7. Message-ID: <4dp98l$in0@null.umd.umich.edu>
  8. References: <31000091.3778302@news.panix.com>
  9. NNTP-Posting-Host: null.umd.umich.edu
  10. NNTP-Posting-User: jlthomas
  11. X-Newsreader: NN version 6.5.0 #3 (NOV)
  12.  
  13. dm@panix.com (Dan'l) writes:
  14.  
  15. >how the outcome of this program is 15.  Somehow one of the B's ends up
  16.  
  17. >#define A 3
  18. >#define B A + A
  19. >#define C B * B
  20.  
  21. >main()
  22. >{
  23. >    printf("%d", C);
  24. >    return 0;
  25. >}
  26.  
  27. Ok Dan, I ran cpp (c pre-processor) over you bit of code and I think that
  28. the answer to you question is apparent now
  29.  
  30. --
  31. # 1 "test.c"
  32.  
  33. main() {
  34.         printf("%d\n",3 + 3 * 3 + 3);
  35.         exit(0);
  36. }
  37. --
  38. 3+3*3+3 => 3+9+3 => 15 the answer you got
  39.  
  40. next you should try
  41.  
  42. #define A (3)
  43. #define B ((A) + (A))
  44. #define C ((B) * (B))
  45.  
  46. which produces C => (((3)) + ((3))) * (((3)) + ((3))) which gives you the
  47. answer that you seek, 36.
  48.  
  49. The important lesson here is that #defines are very very literal in the text
  50. substitution, so you must always use parenthesis and plenty of them to
  51. avoid a mis-interpretation of you code by cpp.
  52. -- 
  53. \|||/  _Spike_Man_      ____  | Jeffery L. Thomas  | "The important thing is
  54.  ^.^  The Internet's   /    \ | jlthomas@umich.edu | not to stop questioning.
  55.   v   first superhero  \ SM / | "This time it will | Curiosity has it own
  56. "more than a cute .sig" \__/  | surely run" - anon | reason for existing."
  57.